package com.darker.secking.service.impl;

import com.darker.secking.entity.User;
import com.darker.secking.exception.GlobalException;
import com.darker.secking.mapper.UserMapper;
import com.darker.secking.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.darker.secking.utils.CookieUtil;
import com.darker.secking.utils.MD5Util;
import com.darker.secking.utils.UUIDUtil;
import com.darker.secking.utils.ValidatorUtil;
import com.darker.secking.vo.LoginVo;
import com.darker.secking.vo.RespBean;
import com.darker.secking.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author darker
 * @since 2022-09-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;



    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

//        if(StringUtils.isEmpty(mobile)|| StringUtils.isEmpty(password)){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
//        }
//        if(!ValidatorUtil.isMobile(mobile)){
//            return RespBean.error(RespBeanEnum.PHONE_ERROR);
//        }
        User user = userMapper.selectById(mobile);
        if(user==null)
        {
           return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }

        String formPass = MD5Util.formPassToDBPass(password, user.getSlat());

        String dbPass = user.getPassword();
        if(!formPass.equals(dbPass)){
            return RespBean.error(RespBeanEnum.PASSWD_ERROR);
        }
        //生成cookid
        String ticket= UUIDUtil.uuid();
       redisTemplate.opsForValue().set("user:"+ticket,user);
        CookieUtil.setCookie(request,response,"userTicket",ticket);

        return RespBean.success(ticket);
    }

    @Override
    public User getUserByCooike(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isEmpty(userTicket)){
           return null;
        }
        User user = (User)redisTemplate.opsForValue().get("user:" + userTicket);
        if(user!=null){
            CookieUtil.setCookie(request,response,"userTicket",userTicket);
        }
        return user;
    }
}
